//
//  FMSButtonWithLoading.m
//  FMS
//
//  Created by Steven on 11/02/13.
//  Copyright (c) 2013 QGSVN. All rights reserved.
//

#import "FMSButtonWithLoading.h"

@interface FMSButtonWithLoading (private)

- (void) commonInit;

@end

@implementation FMSButtonWithLoading (private)

- (void) commonInit {
    _spinWheel = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    _spinWheel.center = CGPointMake(self.frame.size.width / 2.0f, self.frame.size.height / 2.0f);
    _spinWheel.hidesWhenStopped = YES;
    [_spinWheel stopAnimating];
    
    [self addSubview:_spinWheel]; 
    
    self.disableWhileSpinning = YES;
    self.displaySpinnerNextToTitle = YES;
}

@end


@implementation FMSButtonWithLoading

@synthesize disableWhileSpinning = _disableWhileSpinning;
@synthesize displaySpinnerNextToTitle = _displaySpinnerNextToTitle;

- (id)initWithFrame:(CGRect)frame {
    if ((self = [super initWithFrame:frame])) {

        [self commonInit];
    }
    return self;
}

- (void) awakeFromNib{
    [super awakeFromNib];
    [self commonInit];
}

- (void) startActivityIndicator {
    _title = [self titleForState:UIControlStateNormal];
    
    if (self.displaySpinnerNextToTitle) {
        _spinWheel.center = CGPointMake(self.frame.size.width / 2.0f + self.titleLabel.frame.size.width / 2.0f + 15.0f, self.frame.size.height / 2.0f);
    } else {
        [super setTitle:@"" forState:UIControlStateNormal];
    }
    
    [self bringSubviewToFront:_spinWheel];
    [_spinWheel startAnimating];
    
    
    
    if (self.disableWhileSpinning) {
        self.userInteractionEnabled = NO;
    }
}

- (void) stopActivityIndicator {
    [_spinWheel stopAnimating];
    [super setTitle:_title forState:UIControlStateNormal];
    self.userInteractionEnabled = YES;
}

- (void) setTitle:(NSString *)title forState:(UIControlState)state  {
    _title = title;
    [super setTitle:title forState:state];
}

@end
